<template>
  <el-dialog :visible.sync="visible" width="600px" class="part_import">
    <span class="base-import-title" slot="title">{{$t('part.components.partImport.text1', {data1: title})}} <slot name="explain"></slot></span>    
    <div class="import-step">
      <slot name="tip">
        <template v-if="selected.length > 0">
          <span>{{$t('part.components.partImport.text2', {data1: selected.length, data2: title})}}</span>
          <a class="youbian href" @click="downloadData" href="javascript:;">{{$t('common.base.download')}}</a>
        </template>
        <template v-else>
          <span>{{$t('common.bizComponents.bizBatchUpdate.mainContent.step1.0')}}</span>
          <a class=" href" :href="templateBlankUrl">{{$t('common.base.download')}}</a>
          <span>{{$t('common.bizComponents.bizBatchUpdate.mainContent.emptyTemp')}}</span>
        </template>
        <!-- <span v-else>1、您已经选择视图全部数据{{total}}条</span>     -->
      </slot>
    </div>
    <div class="base-import-file">
      <slot name="next">{{$t('part.components.partImport.text3')}}</slot>
      <div class="base-import-file-01">
        <p>{{fileName}}</p>
      <el-button type="primary" @click="choose" :disabled="pending">{{$t('common.base.upload')}}</el-button>
      <input 
        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        type="file" 
        ref="file" 
        @change="change"
      />
      </div>
    </div>
    
    <div class="base-import-error" v-if="errors.length > 0">
      <h5>{{$t('common.base.importModal.tips1')}}</h5>
      <p v-for="(err, index) in errors" :key="index">{{err}}</p>
    </div>

    <div slot="footer">
      <button type="button" class="btn btn-text" @click="visible = false">{{$t('common.base.close')}}</button>
      <el-button type="primary" :disabled="pending" @click="upload" :loading="pending">{{pending ? $t('common.base.importing') : $t('common.base.makeSure')}}</el-button>
    </div>

    <div class="part-export-bridge" ref="bridge"></div>

  </el-dialog>
</template>

<script>
import Uploader from 'packages/BaseUpload/uploader';
import Platform from '@src/util/platform.ts';
import http from '@src/util/HttpUtil';
import { formatDate } from 'pub-bbx-utils';
import { safeNewDate } from '@src/util/time';

export default {
  name: 'part-import',
  inject: ['initData'],
  props: {
    templateUrl: String,
    templateBlankUrl: String, // 空白模板url
    action: String,
    title: {
      type: String,
      default: ''
    },
    selected:{
      type: Array,
      default: []
    },
    total:{
      type: Number,
      default: 0
    },
    templateParams: {
      type: [Object, Array],
      default: () => ({})
    },
    name: {
      type: String,
      default: ''
    },
  },
  data(){
    return {
      fileName: '',
      visible: false,
      pending: false,
      file: null,
      errors: []
    }
  },
  methods: {
    open(){
      this.pending = false;
      this.file = null;
      this.fileName = '';
      this.errors = [];

      this.visible = true;
    },
    choose(){
      this.$refs.file.value = null;
      this.$refs.file.click();
    },
    change(event){
      const files = event.target.files;
      if (!files || files.length == 0) return;
      let file = files[0];

      this.errors = [];
      this.fileName = file.name;
      this.file = file
    },
    upload(){
      if(null == this.file || !(this.file instanceof File)) return Platform.alert(this.$t('common.base.importModal.tips2'));
      this.$confirm(this.$t('part.components.partImport.text4'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel')
      }).then(() => {
        this.pending = true;
        return Uploader.upload(this.file, this.action, {validateStorage: false})
      }).then(result => {
        if(result.status == 0){
          let message = result.message||this.$t('common.base.tip.operationSuccess');
          if(result.data && result.data.total) message += this.$t('part.components.partImport.text6', {data1: result.data.total});

          Platform.alert(message);
          this.visible = false;
          this.$emit('success');
        }else{
          let data = result.data || [];
          this.errors = data;
        }
      })
        .catch(err => {
          console.warn(err)
        })
        .finally(() => {
          this.pending = false;
        })
    },
    downloadData() {
      // /partV2/category/export/update/template?
      let params = this.templateParams;
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}${this.name ? this.name : this.$t('part.components.partImport.text5')}.xlsx`;

      http.post(this.templateUrl, params, true, {responseType: 'blob'})
        .then(blob => {
          let link = document.createElement('a');
          let url = URL.createObjectURL(blob);
          link.download = fileName;
          link.href = url;
          this.$refs.bridge.appendChild(link);
          link.click();

          setTimeout(() => {
            URL.revokeObjectURL(url);
            this.$refs.bridge.removeChild(link);
          }, 150);
        })
        .catch(err => console.warn(err))
    }
  }
}
</script>


<style lang="scss">
.base-import-title{
  display: inline-block;
  min-width: 80px;
  margin-right: 10px;
  line-height: 20px;
  font-size: 16px;
  color: #303133;
}

.import-step{
  margin-bottom:15px;
  line-height:32px;
  .youbian{
    float: right;
    margin-right: 10px;
  }
  .href{
    color: $color-primary-light-6 ;
  }
}
.download-btn{
  text-decoration: none !important;
  border-radius:5px;
  padding:3px 15px;
  color:#606266 !important;
  font-size: 12px;
  border: 1px solid #d5d5d5;
  background-color: #f0f0f0;
  margin-left:20px;
}

.base-import-warn{
  padding: 5px 10px;
  border-radius: 2px;
  background-color: #fdf6ec;
  color: #e6a23c;
  margin-bottom: 15px;
}


.part_import .base-import-file{
  display: block;
  margin-bottom: 15px;
  line-height:32px;
  .base-import-file-01{
    display: flex;
    padding-top: 10px;
  }
  &:last-child{
    margin-bottom: 5px;
  }
  p {
    flex: 1;
    line-height: 24px;
    padding: 3px 6px;

    border: 1px solid #d5d5d5;
    background-color: #f0f0f0;
    border-right: none;
    margin: 0;
    border-radius: 2px 0 0 2px;
  }

  .el-button{
    border-radius: 0 2px 2px 0;
  }

  input[type='file']{
    display: none;
  }
}

.base-import-error{
  max-height: 400px;
  overflow: auto;
  h5{
    font-size: 15px;
    margin: 0;
    line-height: 30px;
    font-weight: 500;
    color: red;
  }

  p{
    margin: 0;
    line-height: 24px;
    word-break: break-all;
  }
}
.title-explain{
  margin: 0;
  padding-left: 20px;
}

.part-export-bridge{
  position: absolute;
  top: -1000px;
  left: -1000px;

  a{
    display: block;
    border: none;
    outline: none;
    width: 0;
    height: 0;
  }
}
</style>
